package com.wpf.system.common.utils.excelListener;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wpf.system.entity.User;
import com.wpf.system.service.UserService;

import java.util.ArrayList;
import java.util.List;

public class UserExcelListener extends AnalysisEventListener<User> {
    private UserService userService;
    private List<User> passList = new ArrayList<>();
    private List<User> failList = new ArrayList<>();
    //每20条存储一次
    private static final int batchCount = 20;
    private int passNum = 0;
    private int failNum = 0;

    public int getPassNum() {
        return passNum;
    }

    public int getFailNum() {
        return failNum;
    }

    public UserExcelListener(UserService userService){
        this.userService = userService;
    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        checkExcel(user);
        if (passList.size() >= batchCount) {
            saveUser();
            // 存储完成清理 list
            passList = ListUtils.newArrayListWithExpectedSize(batchCount);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveUser();
    }

    public void saveUser(){
        for( User user : passList ){ userService.addUser(user); }
    }

    public void checkExcel(User user){
        //表格的数据验证，此处只验证学号是否存在
        User resultUser = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getNid,user.getNid()));
        if(ObjectUtil.isNull(resultUser)){
            passList.add(user);
            passNum++;
        }else{
            failList.add(user);
            failNum++;
        };
    }
}
